<?php
require_once('db.inc.php');
require_once('../lib/fileManager.inc.php');

class photo {
	var $id;
	var $annonce_id;
	var $description;
	var $filename;

	function photo($id=0)
	{
		$this->id = $id;
		if ($this->id != 0) {
    		$rs = sql_query("SELECT * FROM photo WHERE id=" . $this->id);
            $this->annonce_id = $rs->fields['annonce_id'];
            $this->description = stripslashes($rs->fields['description']);
            $this->filename = $rs->fields['filename'];
		}
	}
	
	function reload()
	{
		$this->photo($this->id);
	}
	
	function delete()
	{
        deleteFile('../' . PHOTO_DIR . '/' . $this->filename);
        deleteFile('../' . PHOTO_DIR . '/' . THUMB_PREFIX . $this->filename);
		sql_query("DELETE FROM photo WHERE id=" . $this->id);
	}

	function save()
	{
		global $conn;
		if ($this->id == 0)
		{
		    $sql = "INSERT INTO photo (
		               annonce_id,
		               description,
		               filename
		             ) VALUES (
		               '" . $this->annonce_id . "',
		               '" . addslashes($this->description) . "',
		               '" . $this->filename . "'
		             )";
		}
		else
		{
			$sql = "UPDATE photo SET
			          description='" . addslashes($this->description) . "'
			        WHERE id=" . $this->id . " LIMIT 1";
		}
		if ($conn->Execute($sql) === false) {
		     if ($conn->ErrorNo() == 1062)
                 return ERROR_1062;
             else {
                 log_error("Erreur MySQL dans la SAUVEGARDE d'une photo > " . trim($sql));
                 return ERROR_MYSQL;
             }
        }
        $this->id = $conn->Insert_ID();
        return true;
	}

	function getPhotoIdsFromAnnonceId($annonce_id)
	{
		$data = array();
		$recordSet = sql_query("SELECT * FROM photo WHERE annonce_id=" . $annonce_id);
		while (!$recordSet->EOF) {
			$data[] = $recordSet->fields['id'];
			$recordSet->MoveNext();
		}
		return $data;
	}

	function getNbPhotoFromAnnonceId($annonce_id)
	{
		$data = array();
		$recordSet = sql_query("SELECT COUNT(id) as nb FROM photo WHERE annonce_id=" . $annonce_id);
		return $recordSet->fields['nb'];
	}

	function getRandom($tab)
	{
        if (empty($tab))
            return "default.jpg";
        //TODO: un nombre entre 2 bornes
        return $tab[0]->filename;
	}

}
